package com.zy.pro.paypal;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zy.core.web.BaseController;
import com.zy.pro.order.model.OrderItem;
import com.zy.pro.order.service.OrderItemService;
import com.zy.pro.security.model.Security;
import com.zy.pro.security.service.SecurityService;
import com.zy.pro.security.web.form.SecuritySearchForm;
import com.zy.pro.shop.model.ShopUser;
import com.zy.pro.user.model.User;
import com.zy.utils.SessionUtils;

@Controller
@RequestMapping("/control/ec/expressCheckoutController")
public class ExpressCheckoutController extends BaseController {
	/**
	 * 
	 */
	private static final long serialVersionUID = -2722761580200224133L;	
	
	/**
	 * 订单管理服务类
	 */
	@Resource(name = "orderItemServiceImpl")
	private OrderItemService orderItemService;
	
	/**
	 * 保障金管理服务类
	 */
	@Resource(name = "securityServiceImpl")
	private SecurityService securityService;
    
	@RequestMapping("/doEC")
	public String doEC(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		
		if(!isSet(request.getParameter("L_PAYMENTREQUEST_0_NAME0"))){
			request.setAttribute("error", "Item name cannot be empty!");
			return "control/jsp/error";
		}
		if(!isSet(request.getParameter("L_PAYMENTREQUEST_0_NUMBER0"))){
			request.setAttribute("error", "Item number cannot be empty!");
			return "control/jsp/error";
		}
		if(!isSet(request.getParameter("L_PAYMENTREQUEST_0_DESC0"))){
			request.setAttribute("error", "Item desc cannot be empty!");
			return "control/jsp/error";
		}
		if(!isSet(request.getParameter("PAYMENTREQUEST_0_ITEMAMT"))){
			request.setAttribute("error", "Prices can not be empty!");
			return "control/jsp/error";
		}
		if(!isSet(request.getParameter("PAYMENTREQUEST_0_AMT") )){
			request.setAttribute("error", "Items total cost can not be empty!");
			return "control/jsp/error";
		}
		//物品名称
		String name = request.getParameter("L_PAYMENTREQUEST_0_NAME0");
		//物品编号(保证金S1,订单O1)
		String number = request.getParameter("L_PAYMENTREQUEST_0_NUMBER0");
		//截取ID
		number = number.substring(1, number.length());
		//物品说明
		String desc =  request.getParameter("L_PAYMENTREQUEST_0_DESC0");
		//物品价格
		String itemAmt =  request.getParameter("PAYMENTREQUEST_0_ITEMAMT");
		//总价格
		String allAmt =   request.getParameter("PAYMENTREQUEST_0_AMT");
		//从session中获取店家
    	ShopUser suSession = null;
    	//从session中获取业主
    	User userSession = null;
    	String roleType = SessionUtils.getRoleType(request);
    	if("1".equals(roleType)){
    		userSession = SessionUtils.getUser(request);
    	}else if("2".equals(roleType)){
    		suSession = SessionUtils.getShopUser(request);
    	}
		//判断两个价格是否一致
		if(!itemAmt.equals(allAmt)){
			request.setAttribute("error", "Goods price is not correct!");
			return "control/jsp/error";
		}
		//判断如果是缴付保障金,保障金金额数目是否正确
		if(name.equals("Security")){
			//判断是否是已登录的卖家在缴付保障金
			if(!number.equals(suSession.getShopId().toString())){
				request.setAttribute("error", "seller number is not correct!");
				return "control/jsp/error";
			}
			//获取当前保障金金额
			String securityMoney = "";
			try {
				List<Security> sList = securityService.findAll(new SecuritySearchForm());
				if(!sList.isEmpty()){
					securityMoney = sList.get(0).getSecurityMoney().toString();
				}else{
					request.setAttribute("error", "securityMoney can not be empty!");
					return "control/jsp/error";
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(!itemAmt.equals(securityMoney)){
				request.setAttribute("error", "Goods price is not correct!");
				return "control/jsp/error";
			}
		}else if(name.equals("Order")){
			//判断如果是订单付款,付款数目是否满足当次应付款金额
			try {
				OrderItem oItem = orderItemService.find(number);
				if(oItem != null){
					//判断该订单是否是用户自己的订单
					if(oItem.getOrderUserId() != userSession.getUserId()){
						request.setAttribute("error", "user number is not correct!");
						return "control/jsp/error";
					}
					if(!oItem.getOrderThisMoney().equals(new BigDecimal(itemAmt))){
						request.setAttribute("error", "Goods price is not correct!");
						return "control/jsp/error";
					}
				}else{
					request.setAttribute("error", "order number is not correct!");
					return "control/jsp/error";
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			request.setAttribute("error", "Payment type is not correct!");
			return "control/jsp/error";
		}
		
		
		HttpSession session = request.getSession();
        PayPal pp = new PayPal();
        /*
        '------------------------------------
        ' The returnURL is the location where buyers return to when a
        ' payment has been succesfully authorized.
        '
        ' This is set to the value entered on the Integration Assistant
        '------------------------------------
        */
        //客户选择通过paypal付款后其浏览器将返回到的URL
        //注:paypal建议该参数的值为客户确认订单和付款或者结算协议的最终查看页面
        String returnURL = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/control/ec/returnController/doReturn.do?page=review";
        if(pp.getUserActionFlag().equals("true"))
        	returnURL = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/control/ec/returnController/doReturn.do?page=return";
       
        /*
        '------------------------------------
        ' The cancelURL is the location buyers are sent to when they hit the
        ' cancel button during authorization of payment during the PayPal flow
        '
        ' This is set to the value entered on the Integration Assistant
        '------------------------------------
        */
        //客户不批准使用paypal向您付款时将返回到的URL
        //注:paypal建议该参数的值为客户选择通过paypal付款或签订结算协议的最初页面
        String cancelURL = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/cancel.jsp";
 
        // FIXME - The method 'request.getParameterMap()' must be sanitized before being used.
//		for (String key : request.getParameterMap().keySet()) {
        for (Object k : request.getParameterMap().keySet()) {
        		String key = k.toString();
			   // FIXME - The method 'request.getParameterMap()' must be sanitized before being used.
//			session.setAttribute(key, request.getParameterMap().get(key)[0]);
        	String[] ks = (String[]) request.getParameterMap().get(key);
        	session.setAttribute(key, ks[0]);
			}

        //Redirect to check out page for check out mark
        //重定向到查看页面查看
        if(!isSet(request.getParameter("Confirm")) && isSet(request.getParameter("checkout"))){

    		if(isSet(request.getParameter("checkout")) || isSet(session.getAttribute("checkout"))) {
    			session.setAttribute("checkout", request.getParameter("checkout"));
    		}
    			
	    	//Assign the Return and Cancel to the Session object for ExpressCheckout Mark
	    	//session.setAttribute("RETURN_URL", returnURL);
	    	//session.setAttribute("CANCEL_URL", cancelURL);
	    	session.setAttribute("EXPRESS_MARK", "ECMark");
	    	
	    	request.setAttribute("PAYMENTREQUEST_0_AMT", request.getParameter("PAYMENTREQUEST_0_AMT"));
	    	//redirect to check out page
	    	/*RequestDispatcher dispatcher = request.getRequestDispatcher("checkout.jsp");
	    	if (dispatcher != null){
	    		dispatcher.forward(request, response);
	    	}*/
	    	return "checkout";
	    	
        }
        else{
        	Map<String, String> nvp;        	        	
        	if(isSet(session.getAttribute("EXPRESS_MARK")) && session.getAttribute("EXPRESS_MARK").equals("ECMark")){
	        	if(isSet(request.getParameter("shipping_method"))) {
	        		BigDecimal new_shipping = new BigDecimal(request.getParameter("shipping_method")); //need to change this value, just for testing
	        		BigDecimal shippingamt = new BigDecimal(session.getAttribute("PAYMENTREQUEST_0_SHIPPINGAMT").toString());
	        		BigDecimal paymentAmount = new BigDecimal((String)session.getAttribute("PAYMENTREQUEST_0_AMT"));
	        		if(shippingamt.compareTo(new BigDecimal(0)) > 0){
	        			paymentAmount = paymentAmount.add(new_shipping).subtract(shippingamt) ;
	        		}
	        		session.setAttribute("PAYMENTREQUEST_0_AMT",paymentAmount.toString().replace(".00", ""));
	        		session.setAttribute("PAYMENTREQUEST_0_SHIPPINGAMT",new_shipping.toString());	
	        		session.setAttribute("shippingAmt",new_shipping.toString());
	        	}
	        	returnURL = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/Return.do?page=return";
	        	 nvp = pp.callMarkExpressCheckout(request, returnURL, cancelURL);        	
	        	
        	} else {
        		 nvp = pp.callShortcutExpressCheckout (request, returnURL, cancelURL);
        	}        
	        
			String strAck = nvp.get("ACK").toString().toUpperCase();
	        if(strAck !=null && (strAck.equals("SUCCESS") || strAck.equals("SUCCESSWITHWARNING") ))
	        {
	            session.setAttribute("token", nvp.get("TOKEN").toString());
	            //' Redirect to paypal.com
	            pp.redirectURL(response, nvp.get("TOKEN").toString(),(isSet(session.getAttribute("EXPRESS_MARK")) && session.getAttribute("EXPRESS_MARK").equals("ECMark") || (pp.getUserActionFlag().equalsIgnoreCase("true"))) );
	            return null;
	        }
	        else
	        {
	            // Display a user friendly Error on the page using any of the following error information returned by PayPal
	            String ErrorCode = nvp.get("L_ERRORCODE0").toString();
	            String ErrorShortMsg = nvp.get("L_SHORTMESSAGE0").toString();
	            String ErrorLongMsg = nvp.get("L_LONGMESSAGE0").toString();
	            String ErrorSeverityCode = nvp.get("L_SEVERITYCODE0").toString();
	            
	            String errorString = "SetExpressCheckout API call failed. "+
	           		"<br>Detailed Error Message: " + ErrorLongMsg +
			        "<br>Short Error Message: " + ErrorShortMsg +
			        "<br>Error Code: " + ErrorCode +
			        "<br>Error Severity Code: " + ErrorSeverityCode;
	            request.setAttribute("error", errorString);
	        	/*RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp");
	        	if (dispatcher != null){
	        		dispatcher.forward(request, response);
	        	}*/
	            return "/control/jsp/error";
	        }
//	        return "";
        }
	}
	
	private boolean isSet(Object value){
		return (value !=null && value.toString().length()!=0);
	}
}
